/**
 * 
 */
package cn.springsoter.core.security.strategy.impl;

import java.io.FileNotFoundException;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;

import cn.hutool.core.util.CharsetUtil;
import cn.springsoter.core.security.constant.SecurityConstant;
import cn.springsoter.core.security.strategy.ReadKeyStrategy;
import cn.springsoter.core.tool.utils.KeyStoreUtil;
import cn.springsoter.core.tool.utils.RSAUtil;

/**
 * 从本地读取AES key
 * 
 * @author kevin
 *
 */
@Service
public class ReadAESKeyDefaultStrategy implements ReadKeyStrategy {
	
	private static final String AES_KEY_DEFAULT_CACHE = "AES_KEY_DEFAULT";
	private static Map<String, String> KEY_MAP = Maps.newConcurrentMap();
	
	@Override
	public String readKey() throws FileNotFoundException{
		String key = KEY_MAP.get(AES_KEY_DEFAULT_CACHE);
		if(StringUtils.isBlank(key)) {
			String privateKey = KeyStoreUtil.getKeyFromResources(AES_KEY_DEFAULT_CACHE, "rsa/private.key");
			
			if(StringUtils.isBlank(privateKey)) {
				throw new FileNotFoundException("file: rsa/private.key not exist!");
			}
			
			key = RSAUtil.decryptByPrivateKey(SecurityConstant.AESKEY, RSAUtil.getPrivateKeyFromString(privateKey), CharsetUtil.UTF_8);
			KEY_MAP.put(AES_KEY_DEFAULT_CACHE, key);
		}
		return key;
	}

}
